<template>
  <div class="menu-wrapper">
    <el-form ref="form" :model="form" :rules="rules" label-width="160px">
      <div
        style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px"
      >
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>
      <el-form-item label="注册手机号" prop="mobile">
        <el-col :span="6">
          <el-input v-model="form.mobile" />
        </el-col>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-col :span="6">
          <el-input show-password v-model="form.password" />
        </el-col>
      </el-form-item>
      <el-form-item label="公司名称:" prop="name">
        <el-col :span="6">
          <el-input v-model="form.name" clearable/>
        </el-col>
      </el-form-item>
      <el-form-item label="logo:" prop="logo">
        <single-upload :singleUploadTitle="singleUploadTitle" v-model="form.logo"
                       style="display: inline-block; width: 500px" v-if="imgShow==true"></single-upload>
        <img :src="form.logo" style="width:70px;height:70px" alt="" v-if="form.logo!=null&&imgShow==false">
        <span v-if="form.logo==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="客户类型:" prop="type">
        <el-col :span="6">
          <el-select style="width: 100%" v-model="form.type" clearable placeholder="请选择客户类型">
            <el-option v-for="item in typelist" :key="item.id" :label="item.name" :value="item.id" :disabled="item.id == 1">
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="联系人:" prop="linkman">
        <el-col :span="6">
          <el-input v-model="form.linkman" clearable/>
        </el-col>
      </el-form-item>
      <el-form-item label="联系电话:" prop="phone">
        <el-col :span="6">
          <el-input v-model="form.phone" clearable/>
        </el-col>
      </el-form-item>
      <el-form-item label="详细地址:" prop="address">
        <el-col :span="6">
          <el-input v-model="form.address" clearable/>
        </el-col>
      </el-form-item>
      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">企业资料</span>
      </div>

      <el-form-item label="身份证号:" prop="legalPersonCode">
        <el-col :span="6">
          <el-input v-model="form.metaInfo.legalPersonCode"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="开户行:" prop="bankname">
        <el-col :span="6">
          <el-input v-model="form.metaInfo.bankname"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="开户行账号:" prop="banknum">
        <el-col :span="6">
          <el-input v-model="form.metaInfo.banknum"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="统一社会信用代码:" prop="meta">
        <el-col :span="6">
          <el-input v-model="form.metaInfo.licenseCode"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="身份证正面:" prop="legalPerson1">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.legalPerson1"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.legalPerson1" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.legalPerson1!=null&&imgShow==false">
        <span v-if="form.metaInfo.legalPerson1==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="身份证反面:" prop="legalPerson2">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.legalPerson2"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.legalPerson2" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.legalPerson2!=null&&imgShow==false">
        <span v-if="form.metaInfo.legalPerson2==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="开户许可证:" prop="accountLicense">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.accountLicense"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.accountLicense" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.accountLicense!=null&&imgShow==false">
        <span v-if="form.metaInfo.accountLicense==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="营业执照:" prop="license">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.license"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.license" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.license!=null&&imgShow==false">
        <span v-if="form.metaInfo.license==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="法人代表人授权书:" prop="legalGrant">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.legalGrant"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.legalGrant" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.legalGrant!=null&&imgShow==false">
        <span v-if="form.metaInfo.legalGrant==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="危险化学品经营许可证:" prop="chemical">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.chemical"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.chemical" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.chemical!=null&&imgShow==false">
        <span v-if="form.metaInfo.chemical==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="批发经营证书:" prop="wholesale">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.wholesale"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.wholesale" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.wholesale!=null&&imgShow==false">
        <span v-if="form.metaInfo.wholesale==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="其他证件" prop="other">
        <multi-upload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.other"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></multi-upload>
        <img :src="form.metaInfo.other" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.other!=null&&imgShow==false">
        <span v-if="form.metaInfo.other==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   v-permission="['company.add']"
                   :loading="clicked"
                   @click="saveCompany('form')"
        >保 存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped>
.menu-wrapper {
  margin: 15px;
}
</style>
<script>
import {EventBus} from "@/api/eventBus";
import utils from "../../utils/utils.js";
import {save} from "@/api/company";
import md5 from "js-md5";
import QueryUser from "@/components/Query/queryUser";
import singleUpload from "@/components/Upload/singleUpload";
import {checkUserExists} from "@/api/user";
import permission from "@/directive/permission/index.js"; // 权限判断指令
import multiUpload from "@/components/Upload/multiUpload";
export default {
  name: "company-add",
  directives: {permission},

  filters: {
    watchType(val) {
      if (val == 1) {
        return '经纪人(个人)'
      } else if (val == 2) {
        return '法人企业'
      }
    },

    watchStatus(val) {
      if (val == 1) {
        return '已认证'
      } else {
        return '未认证'
      }
    },
  },
  components: {
    QueryUser,
    singleUpload,
    multiUpload
  },
  data() {
    const checkUser = (rule, value, callback) => { //检查账号是否存在
      if (utils.isNull(value)) {
        callback(new Error("请输入注册手机号"))
      } else {
        const params = new URLSearchParams();
        params.append('username',value)
        checkUserExists(params).then(response => {
          console.log(response)
          if ( response.data !== 0) {
            callback(new Error("该账号已存在，不能重复"))
          } else {
            callback()
          }
        })
      }
    }
    const checkPassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码长度不能小于6位"))
      } else {
        callback()
      }
    }
    return {
      userList: [],
      pageNum: 1,
      pageSize: 20,
      userId: '',
      userName: '',
      imgShow: true,
      singleUploadTitle: "100*100",
      clicked: false, // 按钮防双击
      form: {

        mobile:'',
        password:'',
        name: "",        //公司名称
        logo: "",         //公司Logo
        address: "",	    //详情地址
        linkman: "",	    //联系人
        phone: "",        //联系电话
        meta: "",         //审核资料
        metaInfo: {
          chemical: "",
          license: "",
          licenseCode: null,
          other: "",
          wholesale: "",
          accountLicense: "",
          bankname: "",
          banknum: "",
          legalGrant: "",
          legalPerson1: "",
          legalPerson2: "",
          legalPersonCode: "",

        },
        // msg: "",          //审核说明
        status: 0,        //状态(0.未认证,1.已认证)
        type: '',       //公司类型(1.经纪人(个人),2.法人企业)
      },
      query: {
        userId: '',
        userName: "",
      },
      rules: {
        mobile: [
          { required: true, validator: checkUser, trigger: 'blur' }
        ],
        password: [
          { required: true,  validator: checkPassword, trigger: 'blur' }
        ],
        name: [
          {required: true, message: "请输入公司名称", trigger: "blur"},
          {min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur"}
        ],
        type: [
          {required: true, message: "请选择公司类型", trigger: "blur"}
        ],
        linkman: [
          {required: true, message: "请输入联系人", trigger: "blur"}
        ],
        phone: [
          {required: true, message: "请输入联系电话", trigger: "blur"}
        ],
        legalPerson1: [
          {required: true, message: "请上传身份证正面", trigger: "blur"}
        ],
        legalPerson2: [
          {required: true, message: "请上传身份证反面", trigger: "blur"}
        ],
        legalPersonCode: [
          {required: true, message: "请输入身份证号码", trigger: "blur"}
        ],
      },
      typelist: [
        {
          id: 1,
          name: "经纪人(个人)"
        }, {
          id: 2,
          name: "法人企业"
        }
      ],
    };
  },
  created() {
    var _this = this;
  },

  methods: {
    remoteMethod(query) {
      this.queryUserClick(query)
    },
    queryUserClick(val) {
      // console.log("选择的是", val)
      this.query.userId = val.userId
      this.query.userName = val.name
      this.form.userId = val.userId
      this.form.userName = val.name
      console.log("选择的管理员是", this.form.userName)
    },
    saveCompany(form) {
      const _this = this;
      console.log("form", this.$refs[form].model);
      this.$refs[form].validate(valid => {
        // console.log("点击创建了", valid)
        if(valid == false){
          _this.$message({
            message: "您还有必填项未输入，请您继续完善资料",
            offset: 120,
            center: true,
            type:"warning"
          })
        }
        if (valid) {
          // _this.form.meta = JSON.stringify(_this.form.metaInfo);
          // console.log(_this.form.meta, 'save');
          // 校验表单
          var list = {
            name: _this.form.name,
            logo: _this.form.logo,
            phone: _this.form.phone,
            linkman: _this.form.linkman,
            address: _this.form.address,
            status: 0,
            type: _this.form.type,
          }
          const params = new URLSearchParams();
          params.append('mobile', _this.form.mobile)
          params.append('password', md5(_this.form.password))
          _this.clicked = true;
          save(list,params)
            .then(response => {
              _this.clicked = false;
              if (response.type == "success") {
                let data = response.data;
                console.log("修改完返回给列表的数据--" + JSON.stringify(data));
                EventBus.$emit("company-add", data);
                _this.$store
                  .dispatch("tagsView/delView", _this.$route)
                  .then(({visitedViews}) => {
                    _this.$router.push({
                      path: "/company/list"
                    });
                  }); // 关闭当前tab回到列表
              } else {
                _this.$message({
                  message: response.content,
                  offset: 120,
                  center: true
                });
                console.log("content", response.content);

              }
            })
            .catch(error => {
              _this.clicked = false;
            });
        } else {
          return false;
        }
      });
    },
    //过滤成日期
    formatDate2Day(val) {
      let date = new Date(val);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + MM + "-" + d;
    },
    //过滤到时间
    formatDate2Time(val) {
      let date = new Date(val);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    },
    // 过滤企业列表
    formatList(data) {
      data.createDate = this.formatDate2Day(data.createDate);
      data.modifyDate = this.formatDate2Time(data.modifyDate);
      data.rechangeDate = this.formatDate2Time(data.rechangeDate);
      return data;
    },
  }
};
</script>
